const router = require('koa-router')();
const { sequelize } = require('../common/dbs')

const bloginfoModel = require("../models/bloginfo")
const bloginfo = bloginfoModel(sequelize);
/**
 * 分类管理
 * */
// 查询列表
router.get('/list', async (ctx) => {
    try {
        let reqQuery = ctx.request.query;
        let reData = await bloginfo.findAll(
            {
                where: { is_show: 1 },
                order: [  //排序 DESC ASC
                    ['created_at', 'DESC']
                ],
            }
        );
        // console.log('reData',reData)
        ctx.success(reData)
    } catch (err) {
        ctx.fail(0, err)
    }
})

/**
 * 查询详情
 * name 名字
 * */
router.get('/detail', async (ctx) => {
    try {
        let reqQuery = ctx.request.query;
        console.log('--reqQuery->', reqQuery)
        if (!reqQuery.name) {
            ctx.fail(0, '加载失败')
        }
        let resData = await bloginfo.findOne(
            {
                where: {
                    title_en: reqQuery.name
                },
            }
        );
        console.log(resData)
        if (resData) {
            ctx.success(resData)
        } else {
            ctx.fail(0, err)
            // ctx.success({
            //     title:'404',
            //     content:'404'
            // })
        }
    } catch (err) {
        console.log('err', err)
        ctx.fail(0, err)
    }
})



// 查询列表部分页
router.get('/pageList', async (ctx) => {
    try {
        let reqQuery = ctx.request.query;
        let reData = await bloginfo.findAndCountAll(
            {
                order: [  //排序 DESC ASC
                    ['created_at', 'DESC']
                ],
                limit: reqQuery.limit ? parseInt(reqQuery.limit) : 10,
                offset: reqQuery.page > 0 ? (parseInt(reqQuery.page) - 1) * 10 : 0,
            }
        );
        ctx.success(reData)
    } catch (err) {
        ctx.fail(0, err)
    }
})


// 编辑或者添加
router.post('/editOrAdd', async (ctx) => {
    try {
        ctx
            .validateBody("title")
            .required("名称不能为空")
            .isString()
            .trim()
        ctx
            .validateBody("title_en")
            .required("名称关键字不能为空")
            .isString()
            .trim()

        let reqBody = ctx.request.body;
        let requestData = null
        let msgType = '添加'
        let b = {
            title_en: reqBody.title_en,
            title: reqBody.title,
            content: reqBody.content,
            is_comment: reqBody.is_comment,
            is_show: reqBody.is_show,
            link: reqBody.link,
            type: reqBody.type,
            number: 0
        }

        if (reqBody.id) {
            // 编辑
            requestData = await bloginfo.update(b, {
                where: {
                    id: reqBody.id
                }
            })
            msgType = '修改'
        } else {
            b['id'] = getuuid(12)
            console.log('into=>',b)
            // 新增
            requestData = await bloginfo.create(b)
        }
        if (requestData) {
            ctx.success(msgType + '成功')
        } else {
            ctx.fail(0, msgType + '失败')
        }

    } catch (err) {
        ctx.fail(0, err && err.message)
    }
})
// 删除
router.delete('/del/:id', async (ctx) => {
    try {
        if (!ctx.params.id) {
            ctx.fail(0, 'id不能为空')
        }
        let requestData = await bloginfo.destroy({
            where: {
                id: ctx.params.id
            }
        })
        if (requestData > 0) {
            ctx.success('删除成功')
        } else {
            ctx.fail(0, '内容已删除,或者不存在')
        }
    } catch (err) {
        ctx.fail(0, err)
    }
})

module.exports = router.routes();


function getuuid(max = 32) {
    let s = [];
    let hexDigits = "0123456789abcdef";
    for (var i = 0; i < max; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    if (max > 13) {
        s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
    }
    if (max > 18) {
        s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
    }
    // s[8] = s[13] = s[18] = s[23] = "-";
    var uuid = s.join("");
    return uuid;
}
